-- 桌子的命令，就是 start， reload， delete ,核心是去调用 tablelogic 的函数
local filename = "talkcmd.lua"

local skynet = require "skynet"

local filelog = require "filelog"
local timetool = require "timetool"
local tabletool = require "tabletool"
local timer = require "timer"

local json = require "cjson"
json.encode_sparse_array(true, 1, 1)

require "imenum"

local CMD = {}
local service = nil
local talklogic = nil

function CMD.init(caller)
	service = caller
	talklogic = service:get_logicbyname("talklogic")
end

--
-- 处理cmd类型消息
--
function  CMD.cmd(subcmd,...)
    local f = CMD[subcmd]
    if f == nil then
        return
    end

    return f(...)
end

-- 杀死服务
--
function CMD.kill_service(...)
	service:exit_service()
end

--
-- 从 nodecmd的 createtable()里面调用
--
function CMD.start(conf, attachconf)
	talklogic.init_data(service.talker_data, conf, attachconf)
	return true
end

--
-- 重新加载配置
--
function CMD.reload(conf)
	local talker_data = service.talker_data

	---判断桌子是否在游戏中,如果是在游戏中，将配置文件缓存
	if not tablelogic.is_gameend(talker_data) then
		talker_data.backofconf = tabletool.deepcopy(conf)
		return
	end
	for key, value in pairs(conf) do
		talker_data.conf[key] = value 
	end
end

--
--删除桌子
--
function CMD.delete(delete_reason)
	local talker_data = service.talker_data
	talker_data.isdeleting = true
	--踢出座位上的玩家
    local talk_index = talker_data.index
    talklogic.leavetalk(talker_data, nil)
    --通知router删除table
	skynet.call(".router", "lua", "delete_table", nil, talk_index)
    --关闭服务
	service:exit_service()
end

--
-- 获得桌子数据
--
function CMD.get_table_data()
    local tableobj = service.table_data
    local data = {
        table_index	= tableobj.index,
		table_code	= tableobj.code,
		conf	= tableobj.conf,
		cur_player	= tableobj.sitdown_player_num,
		create_time	= tableobj.create_time,
        create_rid = tableobj.create_rid,
   }
   return data
end

--
-- 获得所有rids
--
function CMD.get_table_allrid()
    local rids = { }
    local tableobj = service.table_data

    for _,seat in pairs(tableobj.seats) do
        if seat.state == ESLWHSeatState.SEAT_STATE_NO_PLAYER 
        or not seat.rid or seat.rid <= 0  then
        
        else
            table.insert(rids,seat.rid)
        end
    end
    for _,w in pairs(tableobj.waits) do
        table.insert(rids,w.rid)
    end
    
   return rids
end

--
-- 获得公开桌列表
-- 正常不会收到，容错处理
--
function CMD.getpubtablelist(rid, roledata)
    return skynet.call(".router","lua","getpubtablelist",nil,rid,roledata)
end

--
-- 获得桌子状态:人数和状态
--
function CMD.gettalkstate()
    local talkobj = service.talker_data
    local sitdown_num = talkobj.sitdown_player_num
    local msg = {
        rid = talkobj.rid,
        total_player = sitdown_num,
        is_vip = talkobj.playerinfo.is_vip,
        last_heart_time = talkobj.last_heart_time,
        isdeleting = talkobj.isdeleting,
    }
    return msg
end

--
-- 定时删除桌子
--
function CMD.delete_talk_by_timer()
    local talkobj = service.talker_data
    talkobj.delete_talk_timer_id = talkobj.delete_talk_timer_id or -1
    if talkobj.isdeleting or talkobj.delete_talk_timer_id > 0 then
        return
    end

    talkobj.delete_talk_timer_id = timer.settimer(5,"delete_talk")
    if talkobj.delete_talk_timer_id < 0 then  --设置定时器失败,则直接删除
        CMD.delete(IMDELETEReason.DELETE_REASON_SYSTEM_ERROR)
    end
end

--
-- 设置桌子结束标记,标记后在一局结束后桌子将被删除
--
function CMD.set_tableend_flag()
    service.table_data.tableend_flag = true

    --如果桌子还未开始游戏直接删除
    if service.table_data.state == ESLWHTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
    or service.table_data.state == ESLWHTableState.TABLE_STATE_WAIT_ALL_READY then
        CMD.delete(ESLWHTableDeleteReason.DELETE_REASON_SYSTEM_REQUIRE)
    end
end

--
--检测桌子状态
--
function  CMD.check_talkstate()
    local talkobj = service.talker_data

    --桌子删除中
    if talkobj.isdeleting then
        return false
    end

    --桌子空位数
    local empty_seat_num = talkobj.conf.max_player_num - talkobj.sitdown_player_num
    
    return empty_seat_num
end

--
--延时离桌
--
function CMD.delay_leave(rid)
    local tableobj = service.table_data

    --游戏中才需要延时离桌
    if not tableobj.is_ingame then
        return false
    end

    for _,seat in pairs(tableobj.seats) do
        if seat.rid == rid then
            seat.is_delayleave = true
            break
        end
    end

    return true
end

--
--获取玩家列表
--
function CMD.get_player_list()
    local tableobj = service.table_data
    local player_list = {}
    for _,seat in pairs(tableobj.seats) do
        if seat.state <= ESLWHSeatState.SEAT_STATE_NO_PLAYER or seat.rid <= 0 then    
        else
            local item = {
                rid = seat.rid,
                logo = seat.playerinfo.logo,
                rolename = seat.playerinfo.rolename,
                game_num = seat.play_game_num,
            }
            table.insert(player_list,item)
        end
    end
    
    return player_list
end

function CMD.push_message(rid, newmessage, since_rid)
    local talkobj = service.talker_data
    --[[
        //im服新消息通知
    message messageN{
        repeated messageitem newmessages = 1;
    }
    --]]
    local noticemsg = {
        newmessages = {},
    }
    local messageitem = {
        keyid               = newmessage.keyid,
        since_rid           = newmessage.since_rid,
        send_to_rid         = newmessage.send_to_rid,
        send_to_name        = newmessage.send_to_name,
        msg                 = newmessage.msg,
        sendtime            = newmessage.sendtime,  ---发送时间
    }

    table.insert(noticemsg.newmessages, json.encode(messageitem))
    ----filelog.sys_error("-------messageN---------", noticemsg)
    talklogic.sendmsg_to_talkplayer(rid, "messageN", noticemsg)
end

return CMD